<template>
<div class='skweatherlive'>
    <nut-overlay v-model:visible="modalshow" :overlay-style="{
      backgroundColor: 'rgba(0, 0, 0, .2)'
    }" :close-on-click-overlay="false">
    </nut-overlay>
    <!-- 实况监测- 天气实况 -->
    <div id="gisApp"></div>
    <div class="hiddenOrShowIcon" :style="{left: leftMenuShow?'32px':'0px'}" @click="leftMenuShow = !leftMenuShow">&gt;</div>
    <div class="elementAddContain" :style="{left: leftMenuShow?'0px':'-50px'}">
        <div @click="leftMenuClick('radar')" :class="[leftMenuActive.indexOf('radar') == -1?'':'active']"><span class="radar"></span><span>天气雷达</span></div>
        <div @click="leftMenuClick('typhoon')" :class="[leftMenuActive.indexOf('typhoon') == -1?'':'active']"><span class="typhoon"></span><span>台风路径</span></div>
        <div @click="changePic"><span class="pic"></span><span>实况统计</span></div>
    </div>
    <div v-show="leftMenuActive.indexOf('typhoon') !=-1" :class="['gisToolBtn_itemChildrenContain', 'typhoon']">
        <div class="typhoonSingle headTitle">
            <!-- <div>
                <el-date-picker style="width: 60px" prefix-icon="" size="small" :clearable="false" @change="getTyphoonList" type="year" v-model="tfYear" value-format="yyyy" format="yyyy" />
            </div> -->
            <div></div>
            <div>编号</div>
            <div>英文名</div>
            <div>中文名</div>
            <div></div>
        </div>
        <div class="typhoonContain">
            <div v-for="typhoon in typhoonList" :key="typhoon.id"  class="typhoonSingle">
                <div>
                    <nut-checkbox v-model="typhoon.isActive" @change="getTyphoonData(typhoon)"></nut-checkbox>
                    <!-- <el-checkbox v-model="typhoon.isActive" @change="getTyphoonData(typhoon)"></el-checkbox> -->
                </div>
                <div :title="typhoon.id">{{typhoon.id}}</div>
                <div :title="typhoon.ename">{{typhoon.ename}}</div>
                <div :title="typhoon.cname">{{typhoon.cname}}</div>
                <div @click="playOrPauseTyphoon(typhoon)"><img :src="typhoon.isPlay?typhoon.playImg:typhoon.pauseImg"></div>
            </div>
        </div>
    </div> 
    <div class="typhoonPopDiv" v-show="typhoonPopDiv.popVisible" :style="{ left: '0px',  top: '320px'}">
      <div class="title">{{typhoonPopDiv.title}}
        <span class="typhoonClose" @click="typhoonPopDiv.popVisible = false">×</span>
      </div>
      <div v-for="item in typhoonPopDiv.content" class="radiuElement">
        <span>{{item.name}}</span>
        <span>{{item.value}}</span>
      </div>
      <div v-if="typhoonPopDiv.radiusContent.length>0" class="radiuContain">
        <div class="radiuTitle">
          <span>风圈半径</span>
          <span>东北</span>
          <span>东南</span>
          <span>西南</span>
          <span>西北</span>
        </div>
        <div v-for="item in typhoonPopDiv.radiusContent" class="radiuContent">
          <span>{{item.text}}</span>
          <span>{{item.ne}}</span>
          <span>{{item.se}}</span>
          <span>{{item.sw}}</span>
          <span>{{item.nw}}</span>
        </div>
      </div>
    </div>
    <div class="hiddenOrShowIconright"  @click="rightMenuShow = !rightMenuShow" :style="{right: rightMenuShow?'80px':'0px'}" >&lt;</div>
    <!-- <div class="picContain" @click="changePic"> 图片</div> -->
    <div class="rightElemCategory" v-show="rightMenuShow">
        <div class="activeElemCateShow">
            <span class="activeElemCateShowIcon">
                <span :class="['cateElemicon',currentSplashElemCate,'iconActive']"></span>
            </span>
            <span>{{getAllElement.name}}</span>
        </div>
        <div class="activeElemCateDiv">
            <div :class="['activeElemCateSingle',currentSplashElemCate == cate.id?'activeCate':'']" v-for="cate in splashData" :key="cate.id" @click="changeCateElem(cate)">
                <span :class="['cateElemicon',cate.id,currentSplashElemCate == cate.id?'iconActive':'']"></span>
                <span>{{cate.name}}</span>
            </div>
        </div>
    </div>
    <div class="rightElem" v-show="rightMenuShow">
        <div class="activeElemShow">{{currentSplashElemItem.name}}</div>
        <div class="activeElemDiv">
            <div :class="['activeElemSingle',currentSplashElemItem.id == elem.id?'activeElem':'']" v-for="elem in getAllElement.children" :key="elem.id" @click="changeElem(elem)">{{elem.name}}</div>
        </div>
    </div>
    <div class="bottomContain">
        <div class="upArrow" @click="bottomClick()"></div>
        <div class="currentTimeInfo" v-show="hiddenBottom">
            <div class="timeShow">
                <span>{{activeTime}}</span>
            </div>
            <div class="currentDotWeather">
                <div class="currentDotWeatherLeft">
                    <div :class="['weather']" v-if="currentWeatherInfo && getWp(currentWeatherInfo.WEA) && getWp(currentWeatherInfo.WEA).src">
                        <img :src="getWp(currentWeatherInfo.WEA).src">
                    </div>
                    <div class="location">
                        <div class="locationCity">{{projectConfig.cityName}}</div>
                        <div class="locationTown">{{projectConfig.cityAddress}}</div>
                    </div>
                </div>
                <div class="currentDotWeatherRight"><span>{{currentWeatherInfo.TMP}}</span><sup>℃</sup></div>
            </div>
            <div class="timeweather"></div>
        </div>
        <div class="legendAndTimeContain" v-show="hiddenBottom">
            <div class="timeConatin">
                <!-- <div :class="['padding','playOrPause']"></div> -->
                <div class="timeDiv">
                    <div class="timeprev" @click="timePrev()"></div>
                    <div class="timeItem">
                        <div v-for="time in timelist" :class="['singleTime',time.isSqurt?'squrt':'round']" @click="timeClick(time)">
                            <span class="textspan">{{time.isSqurt?time.hour:''}}</span>
                            <span :class="['dotspan',activeTime == time.time?'active':'']"></span>
                        </div>

                    </div>
                    <div class="timenext" @click="timeNext()"></div>
                </div>
                
                <!-- <div :class="['padding','timerefresh']"></div> -->
            </div>
            <div class="legendConatin" v-if="currentSplashElemItem.item || currentSplashElemItem.id">
                <!-- <div class="padding"></div> -->
                <div class="legendunit">{{unit}}</div>
                <div class="legendsplashLevel">
                    <div v-for="(color,index) in colors" :key="color" :class="['singleColorVal']">
                        <div class="color" :style="{'background-color':color}"></div>
                        <div class="level">{{levels[index]}}</div>
                    </div>
                </div>
                <!-- <div class="padding"></div> -->
            </div>
        </div>
    </div>

</div>
</template>

<script setup>
import confJson from "@/config/config.json";
import legendconfig from "@/config/legendconfig.js";
import moment from "moment";
import projectConfig from "@/config/projectConf.js";
import { Notify } from '@nutui/nutui'
import '@nutui/nutui/dist/packages/notify/index'
import {queryModelGridDataByRealAndFore,getRadarGridDataLastTime,getRadarGridData,queryTyphoonList,queryTyphoonInfo,findRealDataByLonAndLat} from '@/api/skMountiorApi'
const modalshow = ref(false);
const leftMenuShow = ref(true);
const rightMenuShow = ref(true);
let mapEntity = null;
const cityBorderLayer = ref("cityBorderLayerId")
const initMap = ()=>{
    mapEntity = new GIS.Map({
        mapId: "gisApp",
        conFileUrl: "/mapapi/GIS4.0/items/02NJSZQX/conf/conf.json",//配置文件地址
        // conFile:{
        // 	map: {"constrainResolution": true},
        // 	layers: confJson.gisConfLayer
        // },
        center: projectConfig.mapCenter,
        zoom: projectConfig.mapZoom
    });
    addCityBorder();
    //获取自动站数据
    getAwsGridData();

    getTyphoonList();
}
const currentWeatherInfo = ref({})
const getRealDataByLonAndLat = ()=>{
    findRealDataByLonAndLat(moment().format("YYYYMMDDHH0000"),117.16,34.29).then(res=>{
        currentWeatherInfo.value = res.data;
    })
}
const hiddenBottom = ref(true);

const bottomClick = ()=>{
    hiddenBottom.value = !hiddenBottom.value;
}

const addCityBorder = ()=>{
    if (!mapEntity) {
        return;
    }
    if (mapEntity.getLayerById(cityBorderLayer.value)) {
        mapEntity.removeLayerById(cityBorderLayer.value);
    }
    let data = [{
        id: confJson[projectConfig.projectBorder].attributes.AREACODE,
        coords: confJson[projectConfig.projectBorder].geometry.rings,
        fillColor: "rgba(203,229,241,0)",
        outlineWidth: 2,
        outlineColor: "rgba(208,86,91,1)",
        attribute: {}
    }]
    mapEntity.addLayer(
        new GIS.PolygonLayer(cityBorderLayer.value, data, {zIndex: 11})
    );
}



const router = useRouter()
const changePic =()=>{
    router.push({
        path:"/skweatherlive-pic"
    })
}


const currentSplashElemCate = ref("PRE")
const currentSplashElemItem = ref({})
const splashData = ref([
    {name:'降水',id:'PRE',
        children:[
            {name:'1小时降水',id:'PRE1H', type: ["splash", "number"],modeType:'AWSNC'},
            {name:'3小时降水',id:'PRE3H', type: ["splash", "number"],modeType:'AWSNC'},
            {name:'6小时降水',id:'PRE6H', type: ["splash", "number"],modeType:'AWSNC'},
            {name:'12小时降水',id:'PRE12H', type: ["splash", "number"],modeType:'AWSNC'},
            {name:'24小时降水',id:'PRE24H', type: ["splash", "number"],modeType:'AWSNC'}
        ]
    },
    {name:'气温',id:'TMP',
        children:[
            {name:'温度',id:'TMP', isByMonth:true,type: ["splash", "number"],modeType:'AWSNC'},
        ]
    },
    {name:'风场',id:'EDA',
        children:[
            {name:'瞬时风',id:'WSINS',type: ["splash", "wind"],legendId:"EDA",modeType:'AWSNC'},
            {name:'2分钟平均风',id:'WS2M',type: ["splash", "wind"],legendId:"EDA",modeType:'AWSNC'},
            {name:'10分钟平均风',id:'WS10M',type: ["splash", "wind"],legendId:"EDA",modeType:'AWSNC'},
            {name:'小时内极大风',id:'WSEXT',type: ["splash", "wind"],legendId:"EDA",modeType:'AWSNC'}
        ]
    }
])
currentSplashElemItem.value = splashData.value[0].children[0];
const getAllElement = computed(()=>{
   let data =  splashData.value.filter(item=>item.id == currentSplashElemCate.value);
   return data[0];
})

const getLegend = ()=>{
    const legend = legendconfig["legend"];
    let legendId = currentSplashElemItem.value.legendId?currentSplashElemItem.value.legendId:currentSplashElemItem.value.id
    if(currentSplashElemItem.value.isByMonth){
        legendId = legendId + moment().format("_MM") + "M";
    }
    return legend[legendId];
}
const colors =  computed(()=>{
    let legendData =  getLegend();
    let imageData = legendData["imageData"];
    let newImageData = [];
    for(let i = 0;i<imageData.length/4;i++){
        newImageData.push(`rgba(${imageData[i*4]},${imageData[i*4+1]},${imageData[i*4+2]},1)`)
    }
    return newImageData
})

const levels =  computed(()=>{
    let legendData =  getLegend();
    let level =legendData["labels"] ? legendData["labels"]:legendData["levels"];
    return level;
})
const unit =  computed(()=>{
    let legendData =  getLegend();
    return (legendData && legendData["unit"]) ?legendData["unit"]:''
})

const changeCateElem = (cate)=>{
    if(cate.id != currentSplashElemCate.value){
        clearLayer();
        currentSplashElemCate.value = cate.id;
        let data = splashData.value.filter(item=>item.id == currentSplashElemCate.value)[0];
        currentSplashElemItem.value =  data.children[0];
        getAwsGridData();
    }
}
const changeElem = (elem)=>{
    clearLayer();
    debugger
    if(currentSplashElemItem.value.id == elem.id){
        currentSplashElemItem.value = {};
    }else{
        currentSplashElemItem.value = elem;
        getAwsGridData();
    }
}

const getLayerId = ()=>{
    let layers = [];
    if (currentSplashElemItem.value.type) {
        currentSplashElemItem.value.type.map((type) => {
            layers.push(`${currentSplashElemCate.value}-${currentSplashElemItem.value.id}-${type}Layer`);
        });
    } else {
        layers.push(`${currentSplashElemCate.value}-${currentSplashElemItem.value.id}-SplashLayer`);
    }
    return layers;
}
const addLayer = ()=>{

}
const clearLayer = ()=>{
    const layerId = getLayerId();
    layerId.map((layer) => {
        if (mapEntity.getLayerById(layer)) {
            mapEntity.removeLayerById(layer);
        }
    });
}
const getAwsGridData = ()=> {
    // modalshow.value = true;
    //如果有雷达选中，则删除
    if(leftMenuActive.value.indexOf("radar") !=-1){
        leftMenuActive.value.splice(leftMenuActive.value.findIndex(menu=>menu == "radar"),1);
    }
    clearLayer();
    let resultFun = (res) => {
    debugger
    if (res.byteLength != 0) {
        let coords = confJson.china.geometry.rings;
        let GridData = GIS.RequestHelper.ParseGridData(res);
        let layerIds = getLayerId();
        let legendData =  getLegend();
        
        layerIds.map((item) => {
        if (item.indexOf("splash") != -1) {
            mapEntity.addLayer(
            new GIS.SplashLayer(
                item,
                {
                data: GridData,
                style: {
                    levels: legendData["levels"],
                    imageData: legendData["imageData"],
                    maskRings: coords,
                },
                },
                { zIndex: 1 }
            )
            );
        }
        if (item.indexOf("number") != -1) {
            mapEntity.addLayer(
            new GIS.NumberLayer(
                item,
                {
                data: GridData,
                style: {
                    font: "bold 12px 微软雅黑",
                    color: "rgba(0,0,0,1)",
                    decimal: 1,
                    textSize: 40,
                    maskRings: coords,
                },
                },
                { zIndex: 1 }
            )
            );
        }
        if (item.indexOf("wind") != -1) {
            mapEntity.addLayer(
            new GIS.Windbarb(
                item,
                {
                data: GridData,
                style: {
                    scale: 1,
                    windSize: 30,
                    maskRings: coords,
                },
                },
                { zIndex: 1 }
            )
            );
        }
        });
    } else {
        //this.$message({ type: "warning", message: "无数据" });
    }
    };
    queryModelGridDataByRealAndFore(
        currentSplashElemItem.value.id,
        "SK",
        currentSplashElemItem.value.modeType,
        moment(activeTime.value).format("YYYYMMDDHHmmss"),
        "real-nc",
        currentTimeBef.format("YYYYMMDDHHmmss")
    ).then((res) => {
        modalshow.value = false;
        resultFun(res);
    });
}


//初始化时间
const getNearestTenMinutes = ()=>{
  const now = moment();
  const minutes = now.minutes();
  const roundedMinutes = Math.floor(minutes / 10) * 10;
  return now.minutes(roundedMinutes).seconds(0).subtract(10,'minutes');
}
let timelist = ref([{}])
let currentTimeBef = moment(getNearestTenMinutes());
let currentTime = moment(getNearestTenMinutes());
let activeTime =ref(currentTime.format("YYYY-MM-DD HH:mm:00")) 
timelist.value = [];
timelist.value.unshift({
    time:currentTime.format("YYYY-MM-DD HH:mm:00"),
    isSqurt:Number(currentTime.minutes()) == 0,
    hour:currentTime.format("HH")
})
for(let i = 0;i<12;i++){
    let time = currentTime.subtract(10,'minutes');
    timelist.value.unshift({
        time:time.format("YYYY-MM-DD HH:mm:00"),
        isSqurt:Number(time.minutes()) == 0,
        hour:time.format("HH")
    })
}
const timePrev = ()=>{
    debugger
    let index =timelist.value.findIndex(time=>time.time == activeTime.value);
    index = index-1;
    if(index<0){
        index = 0
    }
    timeClick(timelist.value[index]);
}
const timeClick = (item)=>{
    activeTime.value = item.time;
    clearLayer();
    if(currentSplashElemItem.value.item || currentSplashElemItem.value.id){
        if(currentSplashElemItem.value.item == "radar" || currentSplashElemItem.value.id == "radar"){
            radarActive();
        }else{
            getAwsGridData();
        }
    }
   
}
const timeNext = ()=>{
    debugger
    let index =timelist.value.findIndex(time=>time.time == activeTime.value);
    index = index+1;
    if(index>=timelist.value.length-1){
        index = timelist.value.length-1;
    }
    timeClick(timelist.value[index]);
}

const getWp = (code)=>{
    console.log(code);
    let weatherObj = {
        "0":{
          text:'晴',
          src:new URL(`@/assets/weathers/sun.png`, import.meta.url).href
        },
        "1":{
          text:'多云',
          src:new URL(`@/assets/weathers/cloud.png`, import.meta.url).href
        },
        "2":{
          text:'阴',
          src:new URL(`@/assets/weathers/yin.png`, import.meta.url).href
        },
        "3":{
          text:'阵雨',
          src:new URL(`@/assets/weathers/zhenRain.png`, import.meta.url).href
        },
        "4":{
          text:'雷阵雨',
          src:new URL(`@/assets/weathers/lzy.png`, import.meta.url).href
        },
        "5":{
          text:'雷阵雨并伴有冰雹',
          src:new URL(`@/assets/weathers/lzybb.png`, import.meta.url).href
        },
        "6":{
          text:'雨夹雪',
          src:new URL(`@/assets/weathers/yjx.png`, import.meta.url).href
        },
        "7":{
          text:'小雨',
          src:new URL(`@/assets/weathers/smallRain.png`, import.meta.url).href
        },
        "8":{
          text:'中雨',
          src:new URL(`@/assets/weathers/medRain.png`, import.meta.url).href
        },
        "9":{
          text:'大雨',
          src:new URL(`@/assets/weathers/bigRain.png`, import.meta.url).href
        },
        "10":{
          text:'暴雨',
          src:new URL(`@/assets/weathers/by.png`, import.meta.url).href
        },
        "11":{
          text:'大暴雨',
          src:new URL(`@/assets/weathers/dby.png`, import.meta.url).href
        },
        "12":{
          text:'特大暴雨',
          src:new URL(`@/assets/weathers/tdby.png`, import.meta.url).href
        },
        "13":{
          text:'阵雪',
          src:new URL(`@/assets/weathers/smallSnow.png`, import.meta.url).href
        },
        "14":{
          text:'小雪',
          src:new URL(`@/assets/weathers/smallSnow.png`, import.meta.url).href
        },
        "15":{
          text:'中雪',
          src:new URL(`@/assets/weathers/medSnow.png`, import.meta.url).href
        },
        "16":{
          text:'大雪',
          src:new URL(`@/assets/weathers/bigSnow.png`, import.meta.url).href
        },
        "17":{
          text:'暴雪',
          src:new URL(`@/assets/weathers/bSnow.png`, import.meta.url).href
        },
        "18":{
          text:'雾',
          src:new URL(`@/assets/weathers/w.png`, import.meta.url).href
        },
        "19":{
          text:'冻雨',
          src:new URL(`@/assets/weathers/freeRain.png`, import.meta.url).href
        },
        "20":{
          text:'沙尘暴',
          src:new URL(`@/assets/weathers/scb.png`, import.meta.url).href
        },
        "21":{
          text:'小到中雨',
          src:new URL(`@/assets/weathers/medRain.png`, import.meta.url).href
        },
        "22":{
          text:'中到大雨',
          src:new URL(`@/assets/weathers/bigRain.png`, import.meta.url).href
        },
        "23":{
          text:'大到暴雨',
          src:new URL(`@/assets/weathers/by.png`, import.meta.url).href
        },
        "24":{
          text:'暴雨到大暴雨',
          src:new URL(`@/assets/weathers/dby.png`, import.meta.url).href
        },
        "25":{
          text:'大暴雨到特大暴雨',
          src:new URL(`@/assets/weathers/tdby.png`, import.meta.url).href
        },
        "26":{
          text:'小雪到中雪',
          src:new URL(`@/assets/weathers/medSnow.png`, import.meta.url).href
        },
        "27":{
          text:'中雪到大雪',
          src:new URL(`@/assets/weathers/bigSnow.png`, import.meta.url).href
        },
        "28":{
          text:'大雪到暴雪',
          src:new URL(`@/assets/weathers/bSnow.png`, import.meta.url).href
        },
        "29":{
          text:'浮尘',
          src:new URL(`@/assets/weathers/fc.png`, import.meta.url).href
        },
        "30":{
          text:'扬沙',
          src:new URL(`@/assets/weathers/ys.png`, import.meta.url).href
        },
        "31":{
          text:'强沙尘暴',
          src:new URL(`@/assets/weathers/qscb.png`, import.meta.url).href
        },
        "53":{
          text:'霾',
          src:new URL(`@/assets/weathers/m.png`, import.meta.url).href
        },
        "54":{
          text:'冰雹',
          src:new URL(`@/assets/weathers/lzy.png`, import.meta.url).href
        },
        "55":{
          text:'龙卷',
          src:new URL(`@/assets/weathers/lzy.png`, import.meta.url).href
        },
        "56":{
          text:'雷电',
          src:new URL(`@/assets/weathers/lzy.png`, import.meta.url).href
        }
      }
      if(code !=""){
        return weatherObj[code];
      }else{
        return {
            text:'',
            src:""
        }
      }
}

//雷达
const radarObj = { title: "雷达", type: ["splash"], item: "radar",titleText:'雷达组合反射率',showPrexNextArrow:true,legendId: "MCR", isHiddenMask: true};
//左侧选中菜单
const leftMenuActive = ref([]);
const leftMenuClick = (item)=>{
    clearLayer();
    if(leftMenuActive.value.indexOf(item) == -1){
        leftMenuActive.value.push(item);
        if(item == "radar"){
            radarActive();
        }
    }else{
        leftMenuActive.value.splice(leftMenuActive.value.findIndex(menu=>menu == item),1);
        if(item == "radar"){
            radarRemove();
        }
    }
}


const radarActive = ()=>{
    modalshow.value = true;
    currentSplashElemItem.value = radarObj;
    getRadarGridDataLastTime(moment(activeTime.value).format("YYYYMMDDHHmmss"),1,projectConfig.radarParam).then((res) => {
        const { code, msg } = res;
        if (msg == null || code != 200) {
            Notify.text("查询雷达最新时间失败", { duration: 1000 ,position: 'center',color: '#fff', background: 'rgba(0, 0, 0, 0.7)'});
            modalshow.value = false;
            return;
        }
        getRadarGridData(projectConfig.radarParam, msg).then((res) => {
            modalshow.value = false;
            let legendData =  getLegend();
            let returnData = res.data;
            var gisData = {
                nCols: returnData.nx,
                nRows: returnData.ny,
                ymin: returnData.northLat,
                xmin: returnData.westLon,
                ymax: returnData.southLat,
                xmax: returnData.eastLon,
                xCell: returnData.dx,
                yCell: returnData.dy,
                noDataValue: returnData.invalid,
            };
            let data = {
                data: {
                    rangeObj: gisData,
                    data: returnData.vals,
                },
                style: {
                    levels: legendData["levels"], //颜色阈值
                    imageData: legendData["imageData"],
                    //smooth:true
                },
            };
            let layers = getLayerId();
            layers.map((item) => {
                if (item.indexOf("splash") != -1) {
                    mapEntity.addLayer(new GIS.SplashLayer(item, data, { zIndex: 1 }));
                }
            });
        }).catch((err) => {
            modalshow.value = false;
            Notify.text("查询雷达数据失败", { duration: 1000 ,position: 'center',color: '#fff', background: 'rgba(0, 0, 0, 0.7)'});
        });
    });
}

const typhoonActive = ()=>{}

const radarRemove = ()=>{
    currentSplashElemItem.value = {};
}
const tfYear = ref(moment().format("YYYY"));
let  typhoonList = ref([]);
const typhoonPopDiv = ref({
    popVisible: false,
    title: "",
    content: [],
    radiusContent:[],
    position: {
        top: "",
        left: "",
    },
})
const getTyphoonList = ()=>{
    queryTyphoonList(tfYear.value).then(res=>{
        let {code,data} = res;
        if(code != 200 || !data || data.length == 0){
            typhoonList.value = [];
            return;
        }
        data.map(item=>{
            item.isActive = false;
            item.isPlay = false;
            item.playImg =  new URL(`@/assets/images/skmonitor/typhoonPlay.png`, import.meta.url).href;
            item.pauseImg =  new URL(`@/assets/images/skmonitor/typhoonPause.png`, import.meta.url).href;
        })
        typhoonList.value = data;
    })
}

const getTyphoonData = (typhoon)=>{
    typhoonPopDiv.value.popVisible = false;
    const layerId = "typhoonLayer_"+typhoon.id;
    const layerIdLable = "typhoonLayerLabel_"+typhoon.id;
    mapEntity.getLayerById(layerId)&&mapEntity.removeLayerById(layerId);
    mapEntity.getLayerById(layerIdLable)&&mapEntity.removeLayerById(layerIdLable);
    typhoon.isFirst = false;
    if(!typhoon.isActive){
        let data = typhoonList.value.filter(item=>item.isActive == true);
        if(data.length == 0){
            mapEntity.setCenter([118.88332346072214, 31.862331225255858])
        }
        return;
    };
    modalshow.value = true;
    queryTyphoonInfo(typhoon.id).then(res=>{
        modalshow.value = false;
        let {code,data} = res;
        if(code != 200 || !data|| data.length == 0){
            return;
        }
        let typhoonJsonOne = data[0];
        let typhoonLayer = new GIS.TyphoonLayer(layerId,{
            data:{data:[typhoonJsonOne]},
            fcstsLineStyle: {  // 预测路径样式
                width: 2, // 线宽，默认1
                lineDash: [10, 10] // 虚线样式，默认是[10,10]
            },
            circleStyle: {  //风圈填充颜色
                fillColor: "rgba(21, 45, 78, 0.2)"
            },
            colorFunc: (value) => {  // 颜色函数，根据强度设置不同颜色
                let color = "";
                if (value == 'TD') {
                    color = "rgb(238 209 57)"
                } else if (value == 'TS') {
                    color = "rgb(0 0 255)"
                } else if (value == 'STS') {
                    color = "rgb(15 128 0)"
                } else if (value == 'TY') {
                    color = "rgb(254 156 69)"
                } else if (value == 'STY') {
                    color = "rgb(254 0 254)"
                } else {
                //SSTY
                    color = "rgb(254 0 0)"
                }
                return color
            },
        },{zIndex: 999});
        mapEntity.addLayer(typhoonLayer);
        typhoonLayer.draw();
        mapEntity.addLayer(new GIS.LabelLayer(layerIdLable, [
            {
            id: typhoonJsonOne.id,
            coords: [typhoonJsonOne.lives[0].cell.lon, typhoonJsonOne.lives[0].cell.lat],
            text: typhoonJsonOne.cname,
            font: 'bold 13px 微软雅黑',
            color: "rgba(209,24,17,1)",
            borderColor: "rgba(209,24,17,1)",
            backgroundColor: "rgba(209,24,17,0.2)",
            padding: [2, 2, 2, 2],
            offset: [40, 0],
            }
            
        ], { zIndex: 20, declutter: true }));
        mapEntity.setCenter([typhoonJsonOne.lives[0].cell.lon, typhoonJsonOne.lives[0].cell.lat]);
        typhoonLayer.on("click", e => {
            typhoonPopDiv.value.popVisible = false;
            const atttribute = e.feature.attribute;
            typhoonPopDiv.value.content = [];
            typhoonPopDiv.value.radiusContent = [];
            const point = atttribute.fcstPoint?atttribute.fcstPoint:atttribute.livePoint;
            const type = atttribute.fcstPoint?'预报':'实况';
            typhoonPopDiv.value.title = `${e.id}(${moment(atttribute.time).format("MM月DD日HH时")})  ${type}`;
            typhoonPopDiv.value.content.push({name:'中心位置：', value:point.lon+","+point.lat});
            typhoonPopDiv.value.content.push({name:'强度：', value:`${typhoonIntensity(point.intensity)}`});
            typhoonPopDiv.value.content.push({name:'中心气压：', value:point.pres+"hPa"});
            typhoonPopDiv.value.content.push({name:'移速移向：', value:(point.ms?point.ms:'--')+"m/s("+point.md?point.md:'--'+")"});
            if(atttribute.livePoint){
                typhoonPopDiv.value.radiusContent.push({text:'七级(km)',ne:point.r7ne,se:point.r7se,sw:point.r7sw,nw:point.r7nw});
                typhoonPopDiv.value.radiusContent.push({text:'十级(km)',ne:point.r10ne,se:point.r10se,sw:point.r10sw,nw:point.r10nw});
                typhoonPopDiv.value.radiusContent.push({text:'十二级(km)',ne:point.r12ne,se:point.r12se,sw:point.r12sw,nw:point.r12nw});
            }
            // typhoonPopDiv.value.position.left = e.pixel[0] + 10 + "px";
            // typhoonPopDiv.value.position.top =(e.pixel[1] < 0 ? 0 : e.pixel[1]) + "px";
            typhoonPopDiv.value.popVisible = true;
        });
        typhoonLayer.on("moveout", e => {
           // typhoonPopDiv.value.popVisible = false;
        });
    })
}
const typhoonIntensity = (intensity)=>{
      if(!intensity){
        return '--';
      }
      let intensityText = "热带低压";
      if(intensity == "TS"){
        intensityText = "热带风暴"
      }else if(intensity == "STS"){
        intensityText = "强热带风暴"
      }else if(intensity == "TY"){
        intensityText = "台风"
      }else if(intensity == "STY"){
        intensityText = "强台风"
      }else if(intensity == "SuperTY"||intensity == "SSTY"){
        intensityText = "超强台风"
      }
      return intensityText;
    }
const windGrade = (ws)=>{
    if(!ws){
    return '--级';
    }
    let grade = "0级"
    
    if(ws<= 0.2){
    grade = "0级"
    }else if(ws<= 1.5){
    grade = "1级"
    }else if(ws<= 3.3){
    grade = "2级"
    }else if(ws<= 5.4){
    grade = "3级"
    }else if(ws<= 7.9){
    grade = "4级"
    }else if(ws<= 10.7){
    grade = "5级"
    }else if(ws<= 13.8){
    grade = "6级"
    }else if(ws<= 17.1){
    grade = "7级"
    }else if(ws<= 20.7){
    grade = "8级"
    }else if(ws<= 24.4){
    grade = "9级"
    }else if(ws<= 28.4){
    grade = "10级"
    }else if(ws<= 32.6){
    grade = "11级"
    }else{
    grade = "12级"
    }
    return grade;
}
const playOrPauseTyphoon = (typhoon)=>{
    typhoon.isPlay = !typhoon.isPlay;
    if(typhoon.isPlay && !typhoon.isActive){
        Notify.text("请先显示台风在进行播放", { duration: 1000 ,position: 'center',color: '#fff', background: 'rgba(0, 0, 0, 0.7)'});
        typhoon.isPlay=false;
        return;
    }
    const layerId = "typhoonLayer_"+typhoon.id;
    if(typhoon.isPlay){
    mapEntity.getLayerById(layerId).start(typhoon.id,typhoon.isFirst,()=>{
        typhoon.isPlay = false;
        typhoon.isFirst = false;
    });
    if(!typhoon.isFirst){typhoon.isFirst = true}
    }else{
        mapEntity.getLayerById(layerId).stop(typhoon.id);
        if(typhoon.isPlay){typhoon.isPlay = false;}
    }
}

onMounted(()=>{
    getRealDataByLonAndLat();
    currentSplashElemItem.value = splashData.value[0].children[0];
    let numInterval = setInterval(() => {
        if ('function' === typeof GIS) {
            clearInterval(numInterval);
            initMap();
        }
    }, 50);
})
</script>
<style>
.skweatherlive .nut-checkbox{
    margin-left: 5px;
}
.skweatherlive .nut-checkbox__icon {
    color: #335fd1;
}
</style>
<style scoped lang="scss">
.skweatherlive{
    width: 100%;
    height: 100%;
    font-size: 14px;
    position: relative;
    .typhoonPopDiv{
		font-size: 12px;
		position:fixed;
		left:500px;
		top:20px;
		background:#fff;
		box-shadow: 0px 0px 10px #b9afaf;
		width: 200px;
		height: auto;
		max-height: 350px;
		padding:0px 2px;
		color:#989897;
		.title{
			color:rgb(53, 97, 211);
            position: relative;
            font-weight: bold;
            .typhoonClose{
                position: absolute;
                right: 0px;
                top: -2px;
                color: #989897;
                font-size: 14px;
                font-weight: bold;
                padding: 0px 5px;
            }
		}
		.radiuElement{
			height: 20px;
			line-height: 20px;
		}
		.radiuContain{
			.radiuTitle{
				color: #fff;
                display: flex;
                height: 25px;
                line-height: 25px;
                background: rgb(51, 95, 209);
				>span{
					flex: 1;
					text-align: center;
				}
				>span:first-child{
					flex: 2;
				}
			}
			.radiuContent{
				display: flex;
				height: 20px;
    			line-height: 20px;
				>span{
					flex: 1;
					text-align: center;
				}
				>span:first-child{
					flex: 2;
				}
			}
		}
	}
    .gisToolBtn_itemChildrenContain{
		position: absolute;
        top:120px;
        left: 42px;
		// border-left: 2px solid #07EBF2;
		// background-color: #455562;
        background: #fff;
        border-radius: 5px;
        box-shadow: 0px 0px 10px #b9afaf;
		height: 30px;
		line-height: 30px;
		cursor: pointer;
		&.typhoon{
			height: auto;
			width:200px;
			.typhoonContain{
				max-height: 150px;
    			overflow-y: auto;
			}
			.typhoonSingle{
                border-bottom: 1px solid #989897;
				display: flex;
                align-items: center;
                &.headTitle{
                    background-image:linear-gradient(to right, rgb(79, 128, 250), rgb(51, 95, 209));
                    color: #fff;
                }
				>div{
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
					flex: 1;
                    text-align: center;
					&:first-child,&:last-child{
						flex: 0.5;
					}
                    &:first-child{
                        display: flex;
					}
				}
				&:deep(.el-date-editor) {
					.el-input__prefix {
						left: 0;
					}
					.el-input__suffix {
						display: none;
					}
					.el-input__inner {
						border: none;
						background-color: transparent;
						color: #fff;
						padding-left: 22px;
						padding-right: 0;
						border: none;
					}
					

				}
			}
			&::after{
				border:none;
				content: "";
			}
		}
	}
    #gisApp{
        width: 100%;
        height: 100%;
    }
    .picContain{
        position: absolute;
        bottom: 200px;
        left: 20px;
        background: rgba(255,255,255,0.5);
        border-radius: 5px;
        padding: 2px 8px;
        border:1px solid gray;
        // box-shadow: 0px 0px 3px #333;
    }
    .hiddenOrShowIcon{
        background-color: #fff;
        position: absolute;
        left: 35px;
        bottom:360px;
        // top:10px;
        height: 20px;
        width: 20px;
        text-align: center;
        box-shadow: 2px 0px 3px #b9afaf;
        border-bottom-right-radius: 5px;
        border-top-right-radius: 5px;
        color: #989897;
    }
    .hiddenOrShowIconright{
        background-color: #fff;
        position: absolute;
        right: 65px;
        top:10px;
        height: 20px;
        width: 20px;
        text-align: center;
        box-shadow: 0px 0px 3px #b9afaf;
        border-bottom-left-radius: 5px;
        border-top-left-radius: 5px;
        color: #989897;
    }
    .elementAddContain{
        color: #989897;
        width: 30px;
        height: auto;
        background: #fff;
        border-radius: 5px;
        box-shadow: 0px 0px 10px #b9afaf;
        position: absolute;
        // top:10px;
        bottom:200px;
        left: 0px;
        display: flex;
        flex-direction: column;
        cursor: pointer;
        >div{
            font-size: 12px;
            width: 100%;
            height: 50px;
            display: flex;
            justify-content: center;
            flex-direction: column;
            border-bottom: 1px solid #989897;
            padding:5px 0px;
            &:last-child{
                border-bottom: none;
            }
            >span{
                text-align: center;
                flex: 1;
                background-repeat: no-repeat;
                background-position: center center;
                background-size: 60%;
                &.radar{
                    background-image: url('@/assets/images/skmonitor/radar.png');
                }
                &.typhoon{
                    background-image: url('@/assets/images/skmonitor/typhoon.png');
                }
                &.pic{
                    background-image: url('@/assets/images/skmonitor/pic.png');
                }
            }
            &.active{
                color: rgb(53, 97, 211);
                background: #fff;
                font-weight: bold;
                .radar{
                    background-image: url('@/assets/images/skmonitor/radarActive.png');
                }
                .typhoon{
                    background-image: url('@/assets/images/skmonitor/typhoonActive.png');
                }
                .pic{
                    background-image: url('@/assets/images/skmonitor/picActive.png');
                }
            }
        }
    }
    .rightElemCategory{
        position: absolute;
        top:10px;
        right: 0px;
        .cateElemicon{
            display:inline-block;
            width: 30px;
            height: 100%;
            background-position: center center;
            background-repeat: no-repeat;
            background-size: 70%;
            &.PRE{
                background-image: url('@/assets/images/skmonitor/rain.svg');
                &.iconActive{
                    background-image: url('@/assets/images/skmonitor/rain_active.svg');
                }
            }
            &.TMP{
                background-image: url('@/assets/images/skmonitor/tmp.svg');
                &.iconActive{
                    background-image: url('@/assets/images/skmonitor/tmp_active.svg');
                }
            }
            &.EDA{
                background-image: url('@/assets/images/skmonitor/wind.svg');
                &.iconActive{
                    background-image: url('@/assets/images/skmonitor/wind_active.svg');
                }
            }
        }

        // font-size: 15px;
        .activeElemCateShow{
            display: flex;
            background: rgba(255,255,255,0.8);
            box-shadow: 0px 0px 10px #b9afaf;
            // border-top-left-radius: 10px;
            border-bottom-left-radius: 10px;
            height: 30px;
            line-height: 30px;
            padding:2px;
            // padding:5px 0px;
            color: rgba(53, 97, 211, 1);
            font-weight: bold;
            .activeElemCateShowIcon{
                width: 30px;
                height: 30px;
                background: #e5e9ef;
                border-radius: 50px;
            }
        }
        .activeElemCateDiv{
            padding:2px 15px;
            background: rgba(255,255,255,0.8);
            box-shadow: 0px 0px 10px #b9afaf;
            margin-top: 5px;
            position: relative;
            padding:0px 5px;
            border-radius: 5px;
            &::before{
                transform: rotate(-45deg);
                position: absolute;
                width: 0;
                height: 0;
                top: -4px;
                left: 30px;
                border-right: 5px solid #fff;
                border-top:5px solid #fff;
                border-left: 5px solid transparent;
                border-bottom: 5px solid transparent;
                content: '';
            }
            .activeElemCateSingle{
                text-align: center;
                height: 25px;
                line-height: 25px;
                border-bottom: 1px solid rgba(213, 216, 221, 1);
                color: #989897;
                display: flex;
                &.activeCate{
                    color: #4a9afe;
                    font-weight: bold;
                }
            }
        }
    }
    .rightElem{
        border-top-left-radius: 10px;
        border-bottom-left-radius: 10px;
        position: absolute;
        bottom:200px;
        right: 0px;
        .activeElemShow{
            background: rgba(255,255,255,0.8);
            box-shadow: 0px 0px 10px #b9afaf;
            border-top-left-radius: 10px;
            border-bottom-left-radius: 10px;
            padding:5px 15px;
            color: #4a9afe;
            font-weight: bold;
        }
        .activeElemDiv{
            padding:2px 15px;
            background: rgba(255,255,255,0.8);
            box-shadow: 0px 0px 10px #b9afaf;
            margin-top: 5px;
            position: relative;
            padding:0px 5px;
            border-radius: 5px;
            &::before{
                transform: rotate(-45deg);
                position: absolute;
                width: 0;
                height: 0;
                top: -4px;
                left: 30px;
                border-right: 5px solid #fff;
                border-top:5px solid #fff;
                border-left: 5px solid transparent;
                border-bottom: 5px solid transparent;
                content: '';
            }
            .activeElemSingle{
                text-align: center;
                height: 25px;
                line-height: 25px;
                border-bottom: 1px solid rgba(213, 216, 221, 1);
                color: #989897;
                &.activeElem{
                    color: #3561d3;
                    font-weight: bold;
                }
            }
        }
    }
    .bottomContain{
        width: 100%;
        position: absolute;
        bottom: 0px;
        left: 0;
        right: 0;
        background: rgba(255,255,255,1);
        box-shadow: 0px 0px 10px #b9afaf;
        .upArrow{
            background-image: url('@/assets/images/skmonitor/down.svg');
            background-position: center center;
            background-repeat: no-repeat;
            background-size: 50%;
            background-color: #fff;
            position: absolute;
            left: calc(50% - 20px);
            top: -20px;
            height: 20px;
            width: 40px;
            box-shadow: 0px 0px 10px #b9afaf;
            border-top-left-radius: 10px;
            border-top-right-radius: 10px;
            &.hidden{
                transform: rotate(180deg);
                border-top-left-radius: 0px;
                border-top-right-radius: 0px;
                border-bottom-left-radius: 10px;
                border-bottom-right-radius: 10px;
            }
        }
        .currentTimeInfo{
            .timeShow{
                width: 100%;
                display: flex;
                justify-content: center;
                span{
                    padding: 0px 10px 2px 10px;
                    border-bottom-left-radius: 15px;
                    border-bottom-right-radius: 15px;
                    color: #fff;
                    background-image: linear-gradient(to right,rgba(79, 128, 250, 1), rgba(51, 95, 209, 1));
                }
            }
        }
        .currentDotWeather{
            width: 100%;
            height: 60px;
            display: flex;
            justify-content: space-between;
            .currentDotWeatherLeft{
                flex: 1;
                display: flex;
                .weather{
                    width: 60px;
                    height: 100%;
                    text-align: center;
                    img{
                        width: 60%;
                    }
                    &.sun{
                        background-image: url('@/assets/images/weathers/sunrain.svg');
                        background-position: center top;
                        background-repeat: no-repeat;
                        background-size: 80%;
                    }
                }
                .location{
                    flex: 1;
                    .locationCity{
                        margin-bottom: 5px;
                        font-size: 15px;
                        color: rgba(51, 51, 51, 1);
                    }
                    .locationTown{
                        font-size: 13px;
                        color: rgba(103, 103, 103, 1);
                    }
                }
            }
            .currentDotWeatherRight{
                width: 80px;
                height: 100%;
                color: rgba(103, 103, 103, 1);
                text-align: center;
                span{
                    color: rgba(51, 95, 209, 1);
                    font-weight: bold;
                    font-size: 15px;
                }
            }
        }
        .padding{
            width: 30px;
        }
        .legendAndTimeContain{
            padding:0px 5px;
            box-shadow: 0px 0px 10px #b9afaf;
            .timeConatin{
                width: 100%;
                height: 40px;
                line-height: 15px;
                padding:5px 0px;
                display: flex;
                .playOrPause{
                    background-image: url('@/assets/images/skmonitor/time_pause.png');
                    background-position: center center;
                    background-repeat: no-repeat;
                }
                .timerefresh{
                    background-image: url('@/assets/images/skmonitor/time_refresh.png');
                    background-position: center center;
                    background-repeat: no-repeat;
                }
                .timeDiv{
                    flex: 1;
                    background: rgba(229, 233, 239, 1);
                    border-radius: 5px;
                    display: flex;
                    .timeprev{
                        width: 40px;
                        height: 80%;
                        margin-top: 5px;
                        border-right:1px solid rgba(213, 216, 221, 1);
                        background-image: url('@/assets/images/skmonitor/time_prev.png');
                        background-position: center center;
                        background-repeat: no-repeat;
                    }
                    .timenext{
                        width: 40px;
                        height: 80%;
                        margin-top: 5px;
                        border-left: 1px solid rgba(213, 216, 221, 1);
                        background-image: url('@/assets/images/skmonitor/time_next.png');
                        background-position: center center;
                        background-repeat: no-repeat;
                    }
                    .timeItem{
                        flex: 1;
                        display: flex;
                        .singleTime{
                            flex: 1;
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                            .textspan{
                                color: #333;
                                width: 100%;
                                height: 50%;
                            }
                            &.squrt{
                                text-align: center;
                                .dotspan{
                                    width: 10px;
                                    display: inline-block;
                                    height: 10px;
                                    background: #c3d1df;
                                    &.active{
                                        background: #3561d3;
                                    }
                                }
                            }
                            &.round{
                                text-align: center;
                                margin-top: 8px;
                                .dotspan{
                                    width: 5px;
                                    height: 5px;
                                    display: inline-block;
                                    border-radius: 5px;
                                    background: #c3d1df;
                                    &.active{
                                        background: #3561d3;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            .legendConatin{
                width: 100%;
                height: 15px;
                line-height: 15px;
                padding:5px 0px;
                display: flex;
                .legendunit{
                    width: 40px;
                    text-align: center;
                    font-weight: bold;
                }
                .legendsplashLevel{
                    flex: 1;
                    display: flex;
                    border: 1px solid #333;
                    .singleColorVal{
                        flex: 1;
                        position: relative;
                        .color{
                            width: 100%;
                            height: 100%;
                        }
                        .level{
                            text-align: center;
                            z-index: 9;
                            width: 100%;
                            position: absolute;
                            color: #333;
                            top: 0px;
                            transform: translateX(50%);
                            text-shadow: 0px 0px 3px #fff;
                            font-weight: bold;
                            font-size: 12px;
                        }
                    }
                    
                }
            }
        }
    }
}
</style>